
<template>
  <div v-if="permission||$route.path.includes('/publicReport')"
       class="scorecard_layout_class absolute inset-0 flex flex-col">
    <span class="btnBox"
          @click="showDesign"
          v-if="hasEditPermission&& !showMsg&&$hasPermission('sys:report:reportadmin')">
      <i class="el-icon-more showBtn"></i>
    </span>
    <div class="top-toolbar"
         v-if="showMsg&&$hasPermission('sys:report:reportadmin')">
      <div class="top-toolbar-title"></div>
      <div class="top-toolbar-tool">
        <el-button-group style="position:absolute;right:40px;top:6px;">
          <el-button style="height: 24px;padding: 5px 15px;"
                     icon="el-icon-plus"
                     v-if="editMode && hasEditPermission"
                     size="mini"
                     type="success"
                     v-on:click.native='selectedgadgetPop'>{{ $t('add') }}
          </el-button>
          <el-button size="mini"
                     type="primary"
                     style="height: 24px;padding: 5px 15px;"
                     v-if="hasEditPermission"
                     icon="el-icon-edit"
                     v-on:click.native='toggleClick'
                     ref="toggleBtn">{{ editMode ? 'Save' : 'Design' }}
          </el-button>
          <!-- MB-4780 start -->
          <el-button size="mini"
                     style="height: 24px;padding: 5px 15px;"
                     v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')&&false"
                     icon="el-icon-document-copy">{{ $t('custom.reports.clonebtn') }}
          </el-button>
          <el-button size="mini"
                     v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')&&false"
                     icon="el-icon-printer">{{ $t('custom.reports.botbtn') }}
          </el-button>

          <!-- MB-4780 end -->
        </el-button-group>
        <i class="el-icon-circle-close closeBtn"
           @click="closeDesign"></i>
      </div>
    </div>
    <div v-loading="loading"
         style="min-height:calc(100vh - 120px)">
      <div>
        <grid-layout :layout.sync="gadgets"
                     :col-num="12"
                     :row-height="10"
                     :style="{height:!isShowGridLayout ? '60px':''}"
                     :is-draggable="dashbordDefaultSetting.allowDragging"
                     :is-resizable="dashbordDefaultSetting.allowResizing"
                     :vertical-compact="true"
                     :margin="[12,12]"
                     :use-css-transforms="true">
          <grid-item v-for="(item,index) in gadgets" :data-gadgetType="+isSlicer(item.com)"
                      :x="item.x"
                     :y="item.y"
                     :w="item.w"
                     :h="item.h <2?2:item.h"
                     :i="item.i"
                     :key="item.i"
                     :static="item.static"
                     v-show="item.com==='pageheadergadget' || isShowGridLayout"
                     @container-resized="containerResizedEvent"
                     @resized="resizedEvent"
                     @mouseenter.native="mouseEnterModule(index)"
                     @mouseleave.native="mouseLeaveModule(index,'scorecards')">
            <div class="widget_div" style="width:100;height:100%">
              <div v-if="editMode"
                   class="flex flex-col items-center widget_div_item"
                   style="width:20px;position:absolute;top:4px;right:-22px;z-index:2020;border-left:1px solid #f1f4f5">
                <i @mouseenter="moveComponent(true)"
                   @mouseleave="moveComponent(false)"
                   :title="$t('custom.move')"
                   class="el-icon-rank"
                   v-if="!(item.com==='pageheadergadget')"
                   style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px"></i>
                <!-- v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')" -->
                <i v-if="hasPageHeaderPer(item.com)"
                   @click="editComponent(item.i,item)"
                   :title="$t('custom.edit')"
                   class="el-icon-s-operation"
                   style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px;font-size:14px"></i>
                <i @click="closeComponent(item.i)"
                   :title="$t('custom.remove')"
                   v-if="!(item.com==='pageheadergadget')"
                   class="cuifont icon_delete"
                   style="cursor:pointer;display:inline-block;backgroundColor:#fff;padding:5px;margin-top:5px"></i>
              </div>
              <component :editMode='editMode'
                         :gadgetInfo='item'
                         @dragChanged='gadgetDragChanged'
                         ref="gadgets"
                          style="width:100%;height:calc(100% - 32px)"
                         @removed='gadgetRemoved'
                         :id='item.i'
                         :name="item.name"
                         :loadingStatus="isShowGridLayout"
                         :pageId='pageId'
                         @fullScreen="fullScreen"
                         :presentMode="false"
                         :businessType='businessTypeForWidget'
                         :reportNameForPage='reportNameForPage'
                         :layoutType="layoutType"
                         :is="item.com"></component>
            </div>
          </grid-item>

          <div v-if="gadgets.length === 1"
               style="display: flex;justify-content: center ;align-items:center ;height: 80vh;background: #fff; margin-top:10px;">
            <img :src="$ossLink+'/app/dashboard/dashboard-left.png'"
                 style="height:500px" />
            <div style="margin-left:120px;">
              <div style="font-size: 34px;margin-bottom: 10px;">{{ $t('custom.dashboard.nulldatafirst') }}</div>
              <div style="font-size: 34px;margin-bottom: 15px;">{{ $t('custom.dashboard.nulldatasecond') }}</div>
              <div style="font-size: 20px;margin-bottom: 20px;color: #c8c8c8;">{{ $t('custom.dashboard.nulldatathree') }}
              </div>
              <div>
                <el-button type="success"
                           v-if="hasEditPermission"
                           @click="addgauge">{{ $t('custom.reports.nullwidget') }}
                </el-button>
              </div>
            </div>
          </div>
        </grid-layout>
        <div v-if="!isShowGridLayout"
             style="padding: 0px 10px;">
          <el-card v-if="ganttLoading">
            <div style="display: flex;justify-content: end;margin-bottom: 15px"
                 v-if="editMode">
              <el-button type="primary"
                         size="mini"
                         @click="showSettingDialog">Setting</el-button>
              <el-button type="primary"
                         size="mini"
                         @click="openHeaderDialog()">Add Header</el-button>
            </div>
            <template v-if='showCard'>
              <score-card v-model='sharedDatalist'
                          :columns='columns'
                          :format="layoutSettingForm.topTier.format || 'MMM DD, YYYY'"
                          @change="change"
                          @openHeaderDialog="openHeaderDialog"
                          @scoreCardDrop='saveSort'
                          @changeUserName="changeUserName" />
            </template>
          </el-card>
        </div>
      </div>

      <el-dialog :visible.sync="layoutSettingDialog"
                 title="Scorecard Layout Setting"
                 @closed="clearLayoutSetting"
                 width="420px"
                 :append-to-body="true"
                 :modal-append-to-body="false">
        <el-form :model="layoutSettingForm"
                 :inline="false"
                 ref="layoutSettingForm"
                 label-width="120px"
                 label-position="top"
                 v-loading="layoutSettingLoading">
          <el-form-item label="Top tier Unit">
            <el-select v-model="layoutSettingForm.topTier.unit"
                       @change='topTierFormat'>
              <template v-for="item in dateList">
                <el-option :disabled='item.disabled'
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue">
                </el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="Top tier Format">
            <el-select v-model="layoutSettingForm.topTier.format"
                       default-first-option
                       placeholder="">
              <el-option v-for="item in dateFormatArr"
                         :key="item.id"
                         :value="item.id"
                         :label="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Sort"
                        v-if='false'>
            <el-select v-model="layoutSettingForm.topTier.order">
              <el-option v-for="item in orderOption"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Default View">
            <el-radio v-model="layoutSettingForm.isShowGridLayout"
                      :label='true'>Graphs View</el-radio>
            <el-radio v-model="layoutSettingForm.isShowGridLayout"
                      :label='false'>Table View</el-radio>
          </el-form-item>
          <el-form-item label="Show User Name">
            <el-switch v-model="layoutSettingForm.isShowUserName"></el-switch>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button size="small"
                     @click="clearLayoutSetting">{{ $t('Cancel') }}</el-button>
          <el-button type="primary"
                     size="small"
                     @click="saveLayoutSetting">{{ $t('Save') }}</el-button>
        </template>
      </el-dialog>

      <el-dialog
        :title="isEdit?'Edit Header':'Add Header'"
        :visible.sync="headerVisible"
        :close-on-click-modal="false"
        @close="handleClose"
        width="30%">
        Name  <el-input style="width:80%" v-model="headerName"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button v-if="isEdit" size="mini" type="danger" style="float:left" @click="deleteHeader">{{ $t('Delete') }}</el-button>
          <el-button size="mini" @click="headerVisible = false">{{ $t('Cancel') }}</el-button>
          <el-button size="mini" type="primary" @click="saveHeader">{{ $t('Save') }}</el-button>
        </span>
      </el-dialog>

      <model :showSetting="queryModelDefaultSetting.showSetting"
             @queryModelClosed="queryModelClosed"
             ref="model"
             @refreshDataList="refreshDataList"
             :dataInfo="queryModelDefaultSetting.dataInfo"
             :updateGadget="updateGadget"
             :mappingForm="mappingForm" />
    </div>
    <InterGetStarted :integrationCode="reportIntegrationCode"
                     ref="inter-get-started-dialog" />

    <BDashboardAddWidget v-model="gadgets"
                         :internalWidget="businessTypeForWidget === 'MSPbots Internal'"
                         :internalSlicer="businessTypeForWidget === 'MSPbots Internal'"
                         :widget="businessTypeForWidget !== 'MSPbots Internal'"
                         :slicer="businessTypeForWidget !== 'MSPbots Internal'"
                         scorecard
                         :rootBusinessType="businessTypeForWidget"
                         @event:open-widget-modal="selectGadget"
                         @onAdd="isAddWidget = true"
                         :visible.sync="gadgetChoiceModalVisible" />
    <ShareLinkDialog ref="share-link"
                     source="scorecard"
                     resourceType="ReportHeader" />
    <div class="fullScreenDialog" v-if="isFullScreen">
      <component :editMode='editMode'
                 style="width:100%;height:100%"
                 :gadgetInfo='fullScreenData'
                 @dragChanged='gadgetDragChanged'
                 @removed='gadgetRemoved'
                 @fullScreen="fullScreen"
                 :id='fullScreenData.i'
                 :name="fullScreenData.name"
                 :pageFrom="'reportLayoutFullScreen'"
                 :rolHeight="rolHeight"
                 :comHeight="comHeight"
                 :pageId='pageId'
                 :presentMode="false"
                 :businessType='businessTypeForWidget'
                 :reportNameForPage='reportNameForPage'
                 :is="fullScreenData.com" />
    </div>
  </div>

  <div class="absolute inset-0 flex flex-col"
       v-loading="authLoading"
       v-else>
    <ZContainer>
      <ZEmpty description="No Permission"
              v-if="!authLoading" />
    </ZContainer>
  </div>
</template>

<script>
import Vue from 'vue'
import mixinDashboardViewModule from '@/mixins/dashboard-view-module'
import mixinViewModule from '@/mixins/crud-view-module'
import { dashboardGadgetList, defaultGadgetSettingList } from '@/utils/data-json'
import model from '@/components/gadget/query-model/query-model.vue'
import scoreCard from '@/components/score-card-table/index.vue'

import ComplexWidgetForm from './components/complex-widget-form'
import EmitterMixin from '@/mixins/emitter'
import { getUUID } from '@/utils'
import handleScoreCardData from '@/utils/formatScoreCard'

import ZContainer from '@/components/storybook/z-container'
import ZEmpty from '@/components/storybook/z-empty'
import { getGadget } from '@/components/storybook/hooks/useGadget'

export default {
  name: 'ScorecardLayout',
  mixins: [mixinDashboardViewModule, mixinViewModule, EmitterMixin],
  provide () {
    return {
      getBusinessTypeForWidget: () => this.businessTypeForWidget,
      componentName: 'ScorecardLayout'
    }
  },
  inject: ['refresh'],
  data () {
    return {
      isAddWidget: false,
      reportRelationIntrogrationList: [],
      mixinViewModuleOptions: {
        createdIsNeed: false
      },
      titleTabs: 'title',
      ganttLoading: false,
      sharedDatalist: [],
      currentPage: 1,
      checkedGauge: [],
      dataForm: {
        dataset: ''
      },
      searchVal: '',
      checkedCities: [],
      businessTypeListrecord: [],
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: '',
          gadgetId: '',
          gadgetType: '',
          gadgetSetting: {},
          reuse: true
        }
      },
      isShowGridLayout: false,
      height: '450px',
      renderBaseline: false,
      taskFields: {
        id: 'TaskID',
        name: 'TaskName',
        startDate: 'StartDate',
        progress: 'Progress',
        notes: 'Notes',
        durationUnit: 'Work',
        indicators: 'Indicators'
      },
      gridLines: 'Both',
      labelSettings: {
        taskLabel: ''
      },
      rowHeight: 45,
      dateFormat: 'MMM DD, yyyy',
      dateFormatArr: [],
      columnsKey: {},
      showCard: false,
      order: 'n',
      orderOption: [
        { value: 'o', label: 'ascending' },
        { value: 'n', label: 'descending' }
      ],
      value: '',
      columnDate: [],
      columnFixed: [
        { field: 'userName', headerText: 'User', allowResizing: 'true', textAlign: 'Left', fixed: true, width: '250px' },
        // { field: 'kpi', template: this.kpiButtonComponent, width: 150, headerText: 'KPI', textAlign: 'Left' },
        { field: 'kpi', headerText: 'KPI', allowResizing: 'false', textAlign: 'Left', fixed: true, width: '200px' },
        { field: 'currentValue', headerText: 'Current Value', textAlign: 'Right', width: '140', fixed: true },
        { field: 'benchMark', headerText: 'Benchmark', allowResizing: 'false', width: '120', textAlign: 'Left', fixed: true }
        // { field: 'id', headerText: 'Id', visible: false, allowResizing: 'false', width: '200', textAlign: 'Left', fixed: true }
        // { field: 'edit', template: 'ScorecardBtn', width: '100', textAlign: 'Right', allowResizing: 'false', allowFiltering: 'false', allowSorting: 'false' }

      ],
      dateList: [],
      timelineSettings: {
        timelineUnitSize: 120,
        topTier: {
          format: 'MMM dd, yyyy',
          // ================== MB-15285 START ================== //
          unit: 'Day'
          // ================== MB-15285 END ================== //
        }
        // bottomTier: {
        //   unit: 'Day',
        //   format: 'dd'
        // }
      },
      splitterSettings: {
        columnIndex: 4
      },
      yearformatList: [
        { id: 'MMM YY', format: 'Jan 18' },
        { id: 'YYYY', format: '2018' },
        { id: 'MMMM, YY', format: 'January, 18' }
      ],
      monthformatList: [
        { id: 'MMM dd, yyyy', format: 'Jan 01, 2018' },
        { id: 'MMMMM', format: 'January' },
        { id: 'MMM', format: 'Jan' }
      ],
      weekformatList: [
        { id: 'MMM dd, YYYY', format: 'Jan 01, 2019' },
        { id: 'ddd MMM DD, YY', format: 'Mon Jan 01, YY' },
        { id: 'ddd MMM DD', format: 'Mon Jan 01' }
      ],
      dayformatList: [
        { id: 'YYYY MMM DD', format: '2022 Jan 01' },
        { id: 'MMM DD, YYYY', format: 'Jan 01, 2022' },
        { id: 'MM DD, YY', format: '22 01 01' }
      ],
      layoutSettingDialog: false,
      layoutSettingLoading: false,
      layoutSettingForm: {
        isShowGridLayout: null,
        isBottomTier: false,
        isShowUserName: true,
        topTier: {
          format: '',
          unit: '',
          order: 'n'
        }
      },
      oldOrder: null,
      ScorecardBtn: function () {
        return { template: ScorecardBtn }
      },
      widgets: [],
      headerVisible: false,
      headerName: '',
      isEdit: false,
      editRow: {},
      needCheck: true,
      updateScoreCardOldData: false,
      updateScoreCardOldDataError: false,
    }
  },
  components: {
    model,
    ComplexWidgetForm,
    scoreCard,

    ZContainer,
    ZEmpty
  },

  computed: {
    GadgetList: {
      get () {
        let tempList = []
        tempList = this.userGadgetList.filter(i => i.gadgetType === 'scorecardgadget')
        return tempList
      },
      set (newVal) {
        this.businessTypeListrecord = newVal.filter(i => i.gadgetType === 'scorecardgadget')
      }
    },
    businessTypeList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList
    },
    hasEditPermission () {
      let reportadmin = this.$hasPermission('sys:report:reportadmin') ? 1 : 0
      let editAuth = this.$hasPermission('sys:report:edit') ? 1 : 0
      let isCustom = this.businessTypeForWidget === 'Custom' ? 1 : 0
      if (reportadmin + editAuth + isCustom >= 2) {
        return true
      } else {
        return false
      }
    },
    columns () {
      const data = this.columnFixed.concat(this.columnDate)
      return data
    },
    cronList () {
      try {
        return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'cron_expression_list').dataList
      } catch (error) {
        return []
      }
    }
  },

  watch: {
    userGadgetList (val) {
      this.widgetLoading = false
      this.businessTypeListrecord = this.filterHasWidget(val)
    },
    businessTypeListrecord (val) {
      this.broadcast('PublishedWidget', 'event:get-published-widgets', { widgets: val })
    },
    dialog (newVal) {
      if (newVal) this.widgetLoading = true
    },
    '$store.state.bot.routeMeta': function (val) {
      this.getDashboardLayout()
    },
    dashboardSetting (val) {
      if (val && val.isBottomTier) {
        this.timelineSettings.bottomTier = {
          unit: 'Day',
          format: 'dd'
        }
      }
      if (val && val.isShowGridLayout) {
        this.isShowGridLayout = val.isShowGridLayout
      }
      if (val && val.isShowUserName===false) {
        this.columnFixed = this.columnFixed.filter(v=>v.field!=='userName')
      }else{
        if(!this.columnFixed.find(v=>v.field==='userName')){
          this.columnFixed.unshift({ field: 'userName', headerText: 'User', allowResizing: 'true', textAlign: 'Left', fixed: true, width: '250px' })
        }
      }
    }
    // isShowGridLayout (val) {
    //   if (val) {
    //     this.$refs['gadgets'].forEach(item => item.resized())
    //   }
    // }
  },
  created () {
    this.$on('event:bind-widget', this.bindWidget)
    this.$on('event:open-gadget', this.selectGadget)
    this.$on('event:preview-widget', this.PreviewWidget)
    Vue['_this_scorecard_reports_page'] = this
    this.sharedDatalist = []
    this.initEventBus()
  },
  methods: {
    initEventBus() {
      this.gadgetMessageBus.$on(this.pageId + 'updateSharedDatalist', (e) => {
      if (this.dashboardSetting && this.dashboardSetting.topTier) {
        this.layoutSettingForm.topTier = this.dashboardSetting.topTier
        if (this.layoutSettingForm.topTier.order) {
          this.layoutSettingForm.topTier.order = this.layoutSettingForm.topTier.order ? this.layoutSettingForm.topTier.order : 'n'
          this.oldOrder = this.layoutSettingForm.topTier.order
        }
      }
      this.layoutSettingForm.isShowGridLayout = this.dashboardSetting.isShowGridLayout
      this.layoutSettingForm.isShowUserName=!(this.dashboardSetting.isShowUserName===false)
      if(!this.layoutSettingForm.isShowUserName){
        this.columnFixed=this.columnFixed.filter(v=>v.field!=='userName')
      }
      this.topTierFormat('init')
      this.updateSharedDatalist(e)
    })
    this.gadgetMessageBus.$on(this.pageId + 'isShowGridLayout', (e) => { this.isShowGridLayoutWidget() })
    },
    change () {
      this.refresh()
    },
    eventBus() {
      this.initEventBus()
    },
     isSlicer (val) {
      let obj = dashboardGadgetList.find((item) => {
        return item.key === val
      })
      if (obj && obj.type === 'slicer') {
        return true
      } else {
        return false
      }
    },
    changeUserName (row) {
      const params = {
        gadgetId: row.id,
        includeSql: true
      }
      this.$interface.reports.getReportSettingInfo(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        let saveParams = res.data
        saveParams.gadgetSetting.userId = row.userId
        saveParams.gadgetSetting.userName = row.userName
        saveParams.gadgetSetting.headUrl = row.headUrl
        this.$interface.reports.postReportSetting(saveParams).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
        })
      })
    },
    sortDate () {
      this.showCard = false
      let arr = []
      const reverse = this.oldOrder !== this.layoutSettingForm.topTier.order
      const scoreData = this.sharedDatalist
      this.sharedDatalist = scoreData.map(item => {
        if(item.headerName) {
          return item
        }else {
          const obj = {
            Indicators: item.Indicators,
            TaskID: item.TaskID,
            TaskName: item.TaskName,
            benchMark: item.benchMark,
            conditionFormat: item.conditionFormat,
            currentValue: item.currentValue,
            edit: item.edit,
            headUrl: item.headUrl,
            id: item.id,
            kpi: item.kpi,
            uid: item.uid,
            userName: item.userName,
            userId: item.userId,
            originUserId: item.userId
          }
          const resultData = handleScoreCardData(item.Indicators, this.getDateType(this.layoutSettingForm.topTier.unit), reverse, this.layoutSettingForm.topTier.format, item.conditionFormat, this.layoutSettingForm.topTier.order)
          item = Object.assign({}, obj, ...resultData.data)
          if (arr.length === 0) {
            arr = resultData.columns
          }
          return item
        }
      })
      this.$nextTick(() => {
        this.columnDate = arr
        this.showCard = true
      })
    },
    saveSort () {
      this.saveLayoutSetting()
    },
    getDateType (type) {
      switch (type) {
        case '0 0 0 * * ? *':
          type = 'day'
          break
        case '0 0 0 ? * SUN *':
          type = 'week'
          break
        case '0 0 0 1 * ? *':
          type = 'month'
          break
        default:
          type = 'day'
          break
      }
      return type
    },
    disabledFormatDataSelect (type) {
      const dateKey = {
        day: ['day', 'week', 'month'],
        week: ['week', 'month'],
        month: ['month']
      }
      if (this.cronList && this.cronList.length > 0) {
        this.dateList = this.cronList.map(item => {
          if (dateKey[type].includes(item.subjectCode)) {
            item.disabled = false
          } else {
            item.disabled = true
          }
          return item
        })
      }
    },
    kpiButtonComponent () {
      const that = this
      return {
        template: Vue.component('KpiButton', {
          template: `<el-button type="text" @click="handlePreview" class="kpi-class">{{$data.data.kpi}}</el-button>`,
          methods: {
            handlePreview () {
              that.editComponent(this.$data.data.id, this.$data.data)
            }
          }
        }
        )
      }
    },
    gadgetTypeImgUrl (type) {
      let obj = this._.filter(dashboardGadgetList, { key: type })
      return obj[0].imageUrl || ''
    },
    ganttdataBound () {
      if (Array.isArray(this.sharedDatalist) && this.sharedDatalist.length > 0) {
        for (let i = 0; i < this.sharedDatalist.length; i++) {
          const element = this.sharedDatalist[i].Indicators
          if (Array.isArray(element) && element.length > 0) {
            for (let index = 0; index < element.length; index++) {
              const ele = element[index]
              if (document.getElementsByClassName(ele.iconClass) && document.getElementsByClassName(ele.iconClass).length > 0) {
                var temp = document.getElementsByClassName(ele.iconClass)
                for (let iii = 0; iii < temp.length; iii++) {
                  const element = temp[iii]
                  element.parentNode.style.color = ele.iconClass
                }
              }
            }
          }
        }
      }
    },

    isShowGridLayoutWidget () {
      this.isShowGridLayout = !this.isShowGridLayout
      this.ganttLoading = false
      this.$nextTick(() => {
        this.ganttLoading = true
      })
    },
    showSettingDialog () {
      this.layoutSettingDialog = !this.layoutSettingDialog
    },
    saveLayoutSetting () {
      this.layoutSettingLoading = true
      const obj = this.layoutSettingForm
      obj.sort = this.sharedDatalist.map((item, index) => {
        return {
            sort: index,
            gadgetId: item.id,
            headerName: item.headerName
          }
      })
      const params = {
        id: this.layoutId,
        dashboardSetting: this.layoutSettingForm,
        businessId: this.pageId
      }
      this.$interface.reports.saveLayoutSettingApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          this.layoutSettingLoading = false
          return this.$message.error(res.msg)
        }
        this.sortDate()
        this.timelineSettings = this._.merge(this.timelineSettings, res.data.dashboardSetting)        
        this.clearLayoutSetting()
        let temp = this.isShowGridLayout
        if(res&&res.data&&res.data.dashboardSetting){
          res.data.dashboardSetting.isShowGridLayout = temp
          this.dashboardSetting = res.data.dashboardSetting
        }
      })
    },
    topTierFormat (init) {
      const type = this.layoutSettingForm.topTier.unit
      let temp = []
      switch (type) {
        case 'Year':
          temp = this.yearformatList
          break
        case '0 0 0 1 * ? *':
          temp = this.monthformatList
          break
        case '0 0 0 ? * SUN *':
          temp = this.weekformatList
          break
        case '0 0 0 * * ? *':
          temp = this.dayformatList
          break
        default:
          temp = this.dayformatList
          break
      }
      if (!init) {
        this.layoutSettingForm.topTier.format = temp[0].id
      }
      this.dateFormatArr = temp
    },
    clearLayoutSetting () {
      this.layoutSettingLoading = false
      this.layoutSettingDialog = false
    },
    hasPageHeaderPer (type) {
      let headeradmin = this.$hasPermission('sys:report:pageheaderadmin') ? 1 : 0
      let editadmin = this.$hasPermission('sys:tenant:model:allowtomanage:report:temmodel') ? 1 : 0
      let auth = false
      if (type === 'pageheadergadget') {
        if (headeradmin + editadmin > 1) {
          auth = true
        }
      } else {
        if (editadmin > 0) {
          auth = true
        }
      }
      return auth
    },
   async updateSharedDatalist (dataList) {
      // if (this.updateScoreCardOldData) return false;
      if (dataList.snapShot.length > 0 && !dataList.snapShot[0].id && !this.updateScoreCardOldDataError && !this.isAddWidget) {
        this.updateScoreCardOldData = true
        const params = this.dashboardsDetailsData.contentNew.filter(item => item.com === "scorecardgadget").map(item => item.i)
        const { snapshotRefresh } = this.$interface.reports
        const { data } = await snapshotRefresh(params)
        if (data.code === 0) {
          this.refresh()
        } else {
          // this.updateScoreCardOldDataError = true
        }
      }
      if (this._.find(this.sharedDatalist, { id: dataList.id })) {
        return
      }
      var datalistItem = {
        id: dataList.id,
        uid: dataList.uid,
        TaskID: this.sharedDatalist.length + 1,
        TaskName: dataList.userName,
        userName: dataList.userName,
        userId: dataList.userId,
        originUserId: dataList.userName,
        headUrl: dataList.headUrl,
        kpi: dataList.kpi,
        benchMark: dataList.benchMark,
        currentValue: dataList.currentValue,
        edit: dataList.edit,
        code: dataList.code,
        Indicators: [],
        conditionFormat: dataList.conditionFormat
      }

      datalistItem.Indicators = dataList.snapShot
      this.ganttLoading = false
      const filterData = this.layoutSettingForm.topTier
      const dateType = this.getDateType(filterData.unit || dataList.refreshCron)
      const reverse = filterData.order === 'n'
      const data = handleScoreCardData(datalistItem.Indicators, dateType, reverse, filterData.format, datalistItem.conditionFormat, filterData.order)
      this.disabledFormatDataSelect(this.getDateType(this.value))
      datalistItem = Object.assign({}, datalistItem, ...data.data)
      if (this.columnDate.length === 0) {
        this.columnDate = data.columns
        this.columnsKey = data.columnsKey
      } else {
        data.columns.map((item, index) => {
          if (!this.columnsKey[item.field]) {
            this.columnsKey[item.field] = true
            this.columnDate.splice(index, 0, item)
          }
        })
      }
      this.columnDate.sort((a, b) => {
        return Date.parse(b.sort) - Date.parse(a.sort)
      })
      this.sharedDatalist.push(datalistItem)
      this.showCard = true
      this.ganttLoading = true
      if (this.dashboardSetting && this.dashboardSetting.sort) {
        // const arr = []
        // const unarr = []
        // this.sharedDatalist.map(item => {
        //   let count = 0
        //   this.dashboardSetting.sort.map(items => {
        //     if (item.id === items.gadgetId) {
        //       count = 1
        //       arr.splice(items.sort, 0, item)
        //     }
        //   })
        //   if (count === 0) {
        //     unarr.push(item)
        //   }
        // })
        // this.sharedDatalist = arr.concat(unarr)
        let arrHeader = this.dashboardSetting.sort.filter(i=>i.headerName)
        arrHeader.forEach(iii=>{
          let rr = this.sharedDatalist.some(io=>io.id === iii.gadgetId)
          if(!rr) {
            this.sharedDatalist.push({
              ...iii,
              id:iii.gadgetId
            })
          }
        })
        try {
          this.sharedDatalist.forEach(item=>{
            let res = this.dashboardSetting.sort.find(i=>i.gadgetId === item.id)
            if(res) {
              item.sort = res.sort
            }
          })
          this.sharedDatalist = this.sharedDatalist.sort(function (a, b) {
              return a.sort-b.sort
          })
          this.sharedDatalist.forEach(i=>{
            delete i.sort
          })
        } catch (error) {
          
        }
      }
      this.filterTable()
    },
    filterTable () {
      const userName = []
      const kpi = []
      const currentValue = []
      const benchMark = []
      const userNameObj = {}
      const kpiObj = {}
      const currentValueObj = {}
      const benchMarkObj = {}
      this.sharedDatalist.map(item => {
        if (!userNameObj[item.userName]) {
          userNameObj[item.userName] = true
          userName.push({
            text: item.userName,
            value: item.userName
          })
        }
        if (!kpiObj[item.kpi]) {
          kpiObj[item.kpi] = true
          kpi.push({
            text: item.kpi,
            value: item.kpi
          })
        }
        if (!currentValueObj[item.currentValue]) {
          currentValueObj[item.currentValue] = true
          currentValue.push({
            text: item.currentValue,
            value: item.currentValue
          })
        }
        if (!benchMarkObj[item.benchMark]) {
          benchMarkObj[item.benchMark] = true
          benchMark.push({
            text: item.benchMark,
            value: item.benchMark
          })
        }
      })
      this.columnFixed.map(item => {
        if (item.field === 'userName') {
          item.filter = userName
        }
        if (item.field === 'kpi') {
          item.filter = kpi
        }
        if (item.field === 'currentValue') {
          item.filter = currentValue
        }
        if (item.field === 'benchMark') {
          item.filter = benchMark
        }
        return item
      })
    },
    clearFormData () {
      this.currentPage = 1
      this.searchVal = ''
      this.dataForm.dataset = ''
      this.businessTypeListrecord = []
      this.checkedCities = []
    },

    PreviewWidget (item) {
      this.commandClick(item)
    },
    reportMoreEdit () {
      this.visible = false
      this.$emit('editMoreReportShow', true)
    },
    handleCheckedCitiesChange (value) {
      this.checkedGauge = value
    },
    filterHasWidget (value) {
      let tempList = value
      if (this.businessTypeForWidget !== 'MSPbots Internal') {
        if (this.businessTypeForWidget === 'Template') {
          tempList = this._.reject(tempList, { businessType: 'Custom' })
        }
        tempList = this._.reject(tempList, { businessType: 'MSPbots Internal' })
      }
      let arr = []
      let tempListArr = []
      this.gadgets.forEach(element => {
        arr.push(element.i)
      })
      tempList.forEach(element => {
        if (arr.indexOf(element.gadgetId) === -1) {
          tempListArr.push(element)
        }
      })
      // return tempListArr.filter(i => i.gadgetType === 'scorecardgadget')
      return tempListArr
    },
    checkedName (val) {
      this.currentPage = 1
      if (this.businessTypeForWidget === 'Template') {
        this.GadgetList = this.filterHasWidget(this.userGadgetList).filter(e => e.businessType === 'Template').filter(e => e.name.toLowerCase().indexOf(val.toLowerCase()) !== -1)
      } else {
        this.GadgetList = this.filterHasWidget(this.userGadgetList).filter(e => e.name.toLowerCase().indexOf(val.toLowerCase()) !== -1)
      }
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    showDesign () {
      this.showMsg = !this.showMsg
    },
    closeDesign () {
      this.showMsg = false
      this.editMode = false
    },
    bindWidget ({ widgets }) {
      this.checkedGauge = widgets.map(({ name }) => name)
      this.addGadgetToPageGroup()
      this.broadcast('PublishedWidget', 'event:clear-widgets')
    },
    addGadgetToPageGroup () {
      this.filterHasWidget(this.userGadgetList).forEach(ele => {
        if (this.checkedGauge.includes(ele.name)) {
          this.reportRelationIntrogrationList.concat(ele.integrationCode)
          this.addGadgetToPage(ele)
          this.dialog = false
        }
      })

      this.checkedGauge = []
    },
    commandClick (row) {
      this.queryModelDefaultSetting.dataInfo = {
        ...row
      }
      this.$nextTick(() => {
        this.$store.state.isWidget = true
        this.showQueryModel()
      })
    },
    getIntegrationList (businessId) {
      var _self = this
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      return this.$interface.taskManager.getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (businessId === '1357516578732232706' || businessId === '1357516578732232707') {
            this.checkeConnectNextTicket(res.data)
          } else {
            if (!(_self.gadgets.length === 1 && _self.gadgets[0].com === 'pageheadergadget')) {
              for (const key in res.data) {
                if (Object.hasOwnProperty.call(res.data, key)) {
                  const element = res.data[key]
                  if (_self.reportIntegrationCode.length > 0 && _self.reportIntegrationCode.includes(key) && (element.sync.group === 2 || element.sync.group === 3) && _self.businessTypeForWidget !== 'MSPbots Internal') {
                    _self.$refs['inter-get-started-dialog'].visible = true
                    break
                  }
                }
              }
            }
          }
        }).catch(() => {
        })
    },
    getGadgetSetting (key) {
      return defaultGadgetSettingList.find(e => e.gadgetType === key).gadgetSetting || {}
    },
    selectGadget (record) {
      const { key } = record
      const widget = {
        businessId: '',
        gadgetId: getUUID(),
        gadgetType: key,
        gadgetSetting: this.getGadgetSetting(key),
        reuse: true,
        datasetSetting: {}
      }

      this.showWidgetDesign(widget)
    },
    showWidgetDesign (row) {
      this.queryModelDefaultSetting.dataInfo.datasetSetting = {}
      this.queryModelDefaultSetting.dataInfo = Object.assign(this._.merge(this.queryModelDefaultSetting.dataInfo, row))
      this.queryModelDefaultSetting.showMoreEditSetting = true
      this.$nextTick(() => {
        this.$store.state.isWidget = true
        this.showQueryModel()
      })
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    async queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      const [item] = this.widgets
      const row = getGadget(item)
      const index = this.gadgets.findIndex(record => record.id === row.id)
      if (index !== -1) {
        this.gadgets.splice(index, 1, row)
      } else {
        this.gadgets = this.gadgets.slice(0,1).concat(row,this.gadgets.slice(1))
      }
      this.gadgetChoiceModalVisible = false

      this.query()
    },

    async refreshDataList (widget) {
      this.widgets = [widget]
    },

    updateGadget () {

    },
    mappingForm (to, from) {

    },
    openHeaderDialog(row) {
      if(row) {
        this.isEdit = true
        this.editRow = row
        this.headerName = row.headerName
      }
      this.headerVisible = true
    },
    saveHeader() {
      if(!this.headerName) {
        return this.$message.error('Name cannot be empty')
      }
      if(this.isEdit) {
        this.editRow.headerName = this.headerName
        if(!this.dashboardSetting.sort) {
          this.dashboardSetting.sort = []
        }
        let res = this.dashboardSetting.sort.find(i=>i.gadgetId === this.editRow.id)
        if(res) {
          res.headerName = this.headerName
        }
        this.saveLayoutSetting()
      }else {
        let id = getUUID()
        this.sharedDatalist.unshift({headerName:this.headerName,id:id})
        if(!this.dashboardSetting.sort) {
          this.dashboardSetting.sort = []
        }
        this.dashboardSetting.sort.unshift({headerName:this.headerName,gadgetId:id})
        this.dashboardSetting.sort = this.dashboardSetting.sort.map((i,index)=>{
          return {
            ...i,
            sort:index
          }
        })
      }
      this.$forceUpdate()
      this.headerVisible = false
    },
    deleteHeader() {
      this.sharedDatalist = this.sharedDatalist.filter(i=>i.id !== this.editRow.id)
      if(!this.dashboardSetting.sort) {
          this.dashboardSetting.sort = []
        }
      this.dashboardSetting.sort = this.dashboardSetting.sort.filter(i=>i.gadgetId !== this.editRow.id)
      this.saveLayoutSetting()
      this.$forceUpdate()
      this.headerVisible = false
    },
    handleClose() {
      this.headerName = ''
      this.isEdit = false
    }
  },
  activated ()  {
    this.$root.eventBus.$on('Dashboards-Share', (data, type) => {
      if (data) {
        let url = `${window.location.origin}/publicReport?pageid=${this.dashboardsDetailsData.businessId}&name=${this.dashboardsDetailsData.name}`
        this.$nextTick(() => {
          this.$refs['share-link'].init(this.dashboardsDetailsData, url, type)
        })
      }
    })
  },
  deactivated () {
    this.$root.eventBus.$off('Dashboards-Share')
  },
  beforeCreate () {
    this.$options.components.InterGetStarted = () => import('./intergrations-get-started/index')
  },
  beforeDestroy () {
    this.$root.eventBus.$off('Dashboards-Share')
    delete Vue['_this_scorecard_reports_page']
  }
}
const ScorecardBtn = Vue.component(
  'reports-btn', {
    template: `<div style="display: flex;justify-content: flex-end;">
        <el-button size="mini" plain type="primary" @click="clickSelect('Edit',$data.data)" v-if="hasEditPermission($data.data)">Edit</el-button>
        <el-button size="mini" plain type="danger"  @click="clickSelect('Delete',$data.data)" v-if="hasDeletePermission($data.data)">Delete</el-button>
      </div>`,
    data () {
      return {}
    },

    methods: {
      clickSelect (e, row) {
        Vue['_this_scorecard_reports_page'].socreCommandClick(e, row)
      }
    }
  }
)

</script>

<style lang="scss">
.kpi-class {
  span {
    width: 130px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    display: inline-block;
  }
}
.scorecard_layout_class {
  .e-custom-moments {
    background-color: #fff0;
    border: 1px solid #fff0;
  }
  ::v-deep .select_widget_filter_condition {
    background: url("../../../../assets/select_widget-filter-icon.png");
    background-repeat: no-repeat;
    background-position: center left;
    background-size: 14px 14px;
    padding-left: 20px;
    .filter_condition_lf {
      .filter_condition {
        margin-top: 8px;
        margin-left: 5px;
      }
    }
    .filter_condition_lf > div {
      float: left;
      width: 150px;
      margin-right: 10px;
    }
    .filter_condition_lf > div:nth-child(1) {
      width: auto;
    }
  }
  .select_widget_filter_condition::after {
    content: ".";
    clear: both;
    display: block;
    overflow: hidden;
    height: 0;
  }
  .widget_data_list {
    margin-top: 20px;
    min-height: 20px;
    .el-checkbox-group {
      > .is-checked {
        border: 1px solid #138dc7;
        .el-checkbox__inner {
          // background-image: url('../../../../assets/add_reports_radio_selected.png');
          // background-repeat: no-repeat;
          // background-position: center;
          // background-size: 14px 14px;
        }
        .el-checkbox__inner::after {
          // transform: rotate(0deg) scaleY(0);
        }
      }
      .el-checkbox__inner {
        // border: 0;
        // background-image: url('../../../../assets/add_reports_radio.png');
        // background-repeat: no-repeat;
        // background-position: center;
        // background-size: 14px 14px;
        // background-color: transparent;
      }
    }
    .el-checkted {
      // border: 1px solid #138DC7 !important;
    }
    .el-checkbox {
      display: block;
      margin-right: 0;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      margin-top: 10px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .el-checkbox__input {
        display: block;
        width: 54px;
        text-align: center;
      }
      .el-checkbox__label {
        flex: 1;
        display: block;
        height: 100%;
        padding-left: 0;
        .item_widget {
          // background: url("../../../../assets/grid.png");
          background-size: 48px 48px;
          background-repeat: no-repeat;
          background-position: left center;
          height: 100%;
          // padding-left: 54px;
          padding-top: 5px;
          padding-bottom: 5px;
          display: flex;
          justify-content: space-around;
          align-items: center;
          min-height: 70px;
          .item_widget_content {
            flex: 1;
            height: 100%;
            padding-right: 10px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            > div {
              white-space: pre-wrap;
              word-break: break-word;
            }

            > div:nth-child(1) {
              color: #000;
              font-size: 14px;
            }
            > div:nth-child(2) {
              font-size: 14px;
              color: rgba(0, 0, 0, 0.49);
            }
          }
          .item_widget_ri {
            float: right;
            width: 53px;
            height: 100%;
            text-align: center;
            .item {
              height: 14px;
              width: 14px;
              border: 0;
              background: url("../../../../assets/select_widget_eye.png");
              background-size: 14px 14px;
              background-repeat: no-repeat;
              background-position: center;
            }

            // box-shadow: -1px 0px 0px 0px #F0F0F0;
            // margin: 5px 0;
          }
          position: relative;
        }
        .item_widget::after {
          content: "";
          clear: both;
          display: block;
          overflow: hidden;
          // height: 0;
          position: absolute;
          right: 53px;
          border-right: 1px solid #f0f0f0;
          height: 80%;
        }
      }
    }
    .el-checkbox::after {
      content: ".";
      clear: both;
      display: block;
      overflow: hidden;
      height: 0;
    }
  }
  .el-pagination {
    text-align: center;
  }
  .layoutTitle {
    font-size: 12px;
    word-break: keep-all;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .layoutTitle:hover {
    overflow: visible;
  }

  .vue-grid-item.vue-grid-placeholder {
    background: #f2f8ff;
    border: 1px solid #38f;
    opacity: 1;
  }

  .layoutJSON {
    background: #ddd;
    border: 1px solid black;
    margin-top: 10px;
    padding: 10px;
  }

  .eventsJSON {
    background: #ddd;
    border: 1px solid black;
    margin-top: 10px;
    padding: 10px;
    height: 100px;
    overflow-y: scroll;
  }

  .columns {
    -moz-columns: 120px;
    -webkit-columns: 120px;
    columns: 120px;
  }

  .vue-resizable-handle {
    z-index: 5000;
    position: absolute;
    width: 20px;
    height: 20px;
    bottom: 0;
    right: 0;
    background: url("");
    background-position: bottom right;
    padding: 0 3px 3px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: se-resize;
  }

  .editmode:not(.vue-grid-placeholder) {
    border: 1px solid #38f;
    opacity: 0.5;
  }

  .vue-grid-item.resizing {
    opacity: 0.9;
  }

  .vue-grid-item .no-drag {
    height: 100%;
    width: 100%;
  }

  .vue-grid-item .minMax {
    font-size: 12px;
  }

  .vue-grid-item .add {
    cursor: pointer;
  }

  .vue-draggable-handle {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    left: 0;
    background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><circle cx='5' cy='5' r='5' fill='#999999'/></svg>")
      no-repeat;
    background-position: bottom right;
    padding: 0 8px 8px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: pointer;
  }

  .layout-item {
    text-align: center;
    margin-bottom: 15px;
    padding: 0 5px;
  }

  .layout-item .bottom {
    position: relative;
    margin-top: 15px;
  }

  .layout-item .bottom span {
    display: block;
    float: left;
    width: 50%;
    margin-top: 12px;
    text-align: left;
  }

  .layout-item .bottom button {
    padding-top: 0;
  }

  .top-toolbar {
    position: relative;
    margin-top: -15px;
    height: 35px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    background-color: #fff;
    margin-left: -15px;
    padding-top: 10px;
    width: calc(100% + 30px);
  }

  .top-toolbar .top-toolbar-title {
    padding-left: 25px;
  }

  .btnBox {
    height: 16px;
    padding: 0px 10px;
    background: #c4ebf3;
    position: absolute;
    top: -15px;
    right: 24px;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
  }

  .showBtn {
    font-size: 18px;
    color: #00c4ed;
  }

  .closeBtn {
    font-size: 18px;
    position: absolute;
    top: 8px;
    right: 11px;
  }
  .e-grid .e-content {
    height: 68vh !important;
  }
  .e-gantt .e-gantt-chart .e-chart-root-container .e-content {
    height: 68vh !important;
  }
  .e-gantt .e-gantt-chart .e-label {
    margin-left: 10px;
    text-align: right;
    width: 95px;
    // ================== MB-15285 START ================== //
    // visibility: hidden;
    // &:first-of-type{
    //   visibility: visible;
    // }
    // ================== MB-15285 END ================== //
  }
  .e-treecolumn-container .e-icons {
    width: 0px !important;
  }
  .e-gantt .e-gantt-chart .e-gantt-child-taskbar-inner-div {
    display: none !important;
  }
  .widget_div_item {
    visibility: hidden;
  }
  .widget_div:hover .widget_div_item {
    visibility: visible;
  }
  .widget_div_item:hover {
    visibility: visible;
  }
  .widget_div:hover .more_menu_box {
    display: block;
  }
  .widget_div:hover span.el-icon-more {
    display: block;
  }
}
.fullScreenDialog{
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 1999;
  background: #fff;
}
</style>
